package com.sunday.aomicaichang.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.MenuAdapter;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.model.CookBook;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/1.
 */

public class MenuActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.edit_query)
    ClearEditText editQuery;
    private int pageSize = 20;
    private int pageNumber = 1;
    private LinearLayoutManager layoutManager;
    private MenuAdapter menuAdapter;
    private List<CookBook> cookBookList;
    public int footerState = 0; //0,正在加载 1,没有更多
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        ButterKnife.bind(this);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        menuAdapter = new MenuAdapter(mContext);
        recyclerView.setAdapter(menuAdapter);
        recyclerView.addOnScrollListener(mOnScrollListener);
        if (cookBookList == null) {
            cookBookList = new ArrayList<>();
        }
        initQuery();
        getData();
    }
    String name;
    private void initQuery(){
        editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        editQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    name= editQuery.getText().toString().trim();
                    /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    pageNumber=1;
                    getData();
                    return true;
                } else {
                    return false;
                }
            }

        });

        editQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name= String.valueOf(s);
                pageNumber=1;
                getData();
            }
        });

    }
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {

        private int lastVisibleItem;

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = layoutManager.findLastVisibleItemPosition();
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == menuAdapter.getItemCount()
                    && getFooterState() == 0) {
                //加载更多
                pageNumber++;
                getData();
            }
        }
    };
    public int getFooterState() {
        return footerState;
    }
    public void setFooterState(int footerState) {
        this.footerState = footerState;
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String size = String.valueOf(pageSize);
        String number = String.valueOf(pageNumber);
        String[] str1 = new String[]{ "name","pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{ name,size, number, nonce};
        if(pageNumber==1)
            showLoadingDialog(0);
        Call<ResultDO<List<CookBook>>> call = ApiClient.getApiAdapter().menu(name, pageSize, pageNumber,
                nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<CookBook>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<CookBook>>> call, Response<ResultDO<List<CookBook>>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<List<CookBook>> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    List<CookBook> cookBooks = resultDO.getResult();
                    if (pageNumber == 1)
                        cookBookList.clear();
                    cookBookList.addAll(cookBooks);
                    if (cookBooks.size() >= 0 && cookBooks.size() < pageSize ) {
                        setFooterState(1);
                    } else {
                        setFooterState(0);
                    }
                    menuAdapter.setmData(cookBookList);
                    menuAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<CookBook>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }
}
